package com.gancp.common.security;


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

    public static final String KEY_ALGORITHM = "AES";
    public static final String KEY_ALGORITHM_MODE = "AES/CBC/PKCS5Padding";
    public static final String CHARSET_NAME = "UTF-8";

    private AESUtil() {
    }

    public static String encrypt(String input, String key) {
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec( key.getBytes( CHARSET_NAME ), KEY_ALGORITHM );
            Cipher cipher = Cipher.getInstance( KEY_ALGORITHM_MODE );
            cipher.init( Cipher.ENCRYPT_MODE, skey, new IvParameterSpec( new byte[cipher.getBlockSize()] ) );
            crypted = cipher.doFinal( input.getBytes( "UTF-8" ) );
            return Base64Util.encode( crypted );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String input, String key) {
        try {
            SecretKeySpec skey = new SecretKeySpec( key.getBytes( CHARSET_NAME ), KEY_ALGORITHM );
            Cipher cipher = Cipher.getInstance( KEY_ALGORITHM_MODE );
            cipher.init( Cipher.DECRYPT_MODE, skey, new IvParameterSpec( new byte[cipher.getBlockSize()] ) );
            byte[] originBytes = Base64Util.decode( input );
            byte[] result = cipher.doFinal( originBytes );
            return new String( result, CHARSET_NAME );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void main(String[] args) throws Exception {
        // AES加密数据
        String key = "1234567890abcdef";
        String dataToEn = "{'mobile':'18702604727','code':'6666','platform':'android'}";
        String enresult = encrypt( dataToEn, key );
        System.out.println( enresult );
        //String deresult = decrypt( enresult, key );
        //System.out.println( deresult );
        // RSA  加密AES密钥
        byte[] enkey = RSAUtil.encryptByPublicKey( key.getBytes( CHARSET_NAME ), RSAUtil.PUBLIC_KEY );
        // System.out.println( new String( enkey, "UTF-8" ) );
        String basekey = Base64Util.encode( enkey );
        System.out.println( basekey );

      /*  // 解密
        byte[] dere = Base64Util.decode( basekey );
        byte[] result = RSAUtil.decryptByPrivateKey( dere );
        System.out.println( new String( result, "UTF-8" ) );
        String deR = decrypt( enresult, key );
        System.out.println(deR);*/
    }
}
